<template>
  <Drawer placement="right" :closable="true" v-model="visible" width="400" scrollable @on-close="cancel">
    <template #header>
      <div class="flex flex-col justify-between">
        <div class="flex items-center mb-4 gap-x-2">
          <img src="~@/assets/images/icon_discussion.jpeg" class="w-6 h-6" alt="Start icon" />
          <div class="flex flex-col gap-y-1">
            <p class="text-lg font-semibold text-black">{{ title }}</p>
          </div>
        </div>
        <div class="text-sm text-gray-500">
          {{ desc }}
        </div>
      </div>
    </template>

    <CommonCollapse title="输入" tip="输入需要添加到提示词的信息，这些信息可以被下方的提示词引用">
      <div class="panel-table">
        <div class="panel-table-header">
          <div class="name" style="width: 150px">变量名</div>
          <div class="name">变量值</div>
        </div>
        <div class="panel-table-list">
          <Form ref="formEl" :model="form" label-position="top">
            <div class="flex items-center mb-4" v-for="(item, index) in form.inoutlist" v-if="form">
              <div class="panel-table-item" style="width: 160px">
                <FormItem :key="index" prop="name">
                  <span>{{ item.varname }}</span>
                  <span class="faid-type">File/Doc</span>
                </FormItem>
              </div>
              <div class="panel-table-item" style="width: 180px">
                <FormItem
                  :prop="'inoutlist.' + index + '.varparam'"
                  :rules="{
                    required: true,
                    message: '变量值不可为空',
                    trigger: 'blur'
                  }"
                >
                  <div class="upload-btn">
                    <Icon type="ios-folder-outline" size="16"></Icon>

                    <Upload :before-upload="beforeUpload">
                      <template v-if="!item.varparam">
                        <Icon type="md-cloud-upload" size="16"></Icon>
                        <div>上传文件</div>
                      </template>
                      <div class="file-context" v-else @click.stop>
                        <span>{{item.varparam}}</span>
                        <Icon v-if="!fileLoading" type="ios-close" size="20" @click="item.varparam = ''" />
                        <Icon v-else type="ios-loading" size="20" />
                      </div>
                    </Upload>
                  </div>
                </FormItem>
              </div>
            </div>
          </Form>
        </div>
      </div>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="知识库" tip="选择需要匹配的知识范围，仅从选定的知识中召回信息">
      <template v-if="!knowledgeList.length" #right>
        <Button type="primary" size="small" icon="md-add" @click="showModal = true"></Button>
      </template>

      <ul class="knowledge-gather">
        <li v-for="item in knowledgeList" :key="item.id">
          <div class="label">
            <img src="@/assets/images/dataset_text.png" alt="" />
            <span>{{ item.name }}</span>
          </div>

          <Button
            type="text"
            icon="ios-trash"
            @click="form.knowledgeid = ''"
          ></Button>
        </li>
      </ul>

      <template v-if="knowledgeList.length">
        <p class="ans-label">文档解析策略</p>

        <ul class="flex items-center ans-type">
          <li
            v-for="(item, index) in DOCSTRATEGY_OPTIONS"
            :key="index"
            :class="{ avtive: form.docstrategy === item.value }"
            @click="form.docstrategy = item.value"
          >
            <span>{{ item.label }}</span>
            <Tooltip :content="item.desc" theme="light" placement="top" transfer max-width="400">
              <Icon type="ios-alert-outline" size="16" />
            </Tooltip>
          </li>
        </ul>

        <CheckboxGroup
          v-if="form.docstrategy === DOCSTRATEGY_OPTIONS[1].value"
          class="checkbox-content"
          v-model="form.precise"
        >
          <Checkbox v-for="(item, index) in PRECISE_OPTIONS" :key="index" :label="item.value">
            {{ item.label }}
          </Checkbox>
        </CheckboxGroup>

        <p class="ans-label">分段策略</p>

        <ul class="flex items-center ans-type">
          <li
            v-for="(item, index) in SEGMENTATION_OPTONS"
            :key="index"
            :class="{ avtive: form.segmentstrategy === item.value }"
            @click="form.segmentstrategy = item.value"
          >
            <span>{{ item.label }}</span>
            <Tooltip :content="item.desc" theme="light" placement="top" transfer max-width="400">
              <Icon type="ios-alert-outline" size="16" />
            </Tooltip>
          </li>
        </ul>

        <ul v-if="form.segmentstrategy === SEGMENTATION_OPTONS[1].value" class="strategy-content">
          <li>
            <div class="label">
              <span>分段标识符</span>
              <Tooltip
                content="按照所选的标识符切分文本"
                theme="light"
                placement="top"
                transfer
                max-width="400"
              >
                <Icon type="ios-alert-outline" size="16" />
              </Tooltip>
            </div>

            <Select v-model="form.segmenttag" size="small">
              <Option v-for="(item, index) in SYMBOL_TYPE_OPTIONS" :value="item.value" :key="index">
                {{ item.label }}</Option
              >
            </Select>
          </li>

          <Input
            v-if="form.segmenttag === 'LinebreakCustomize'"
            class="custom-selice"
            v-model="form.content"
            placeholder="请输入分段标识符"
          ></Input>

          <li>
            <div class="label">
              <span>分段最大长度</span>
              <Tooltip
                content="切分后单个切片允许的最大长度"
                theme="light"
                placement="top"
                transfer
                max-width="400"
              >
                <Icon type="ios-alert-outline" size="16" />
              </Tooltip>
            </div>

            <Slider v-model="form.segmentmaxilength" :min="100" :max="5000" :marks="marks"></Slider>
          </li>

          <li>
            <div class="label">
              <span>分段重叠度%</span>
              <Tooltip
                content="相邻切片之间的重叠度比例,重叠切片可以确保重要信息不会在切片边界处丢失,为模型提供更多上下文"
                theme="light"
                placement="top"
                transfer
                max-width="400"
              >
                <Icon type="ios-alert-outline" size="16" />
              </Tooltip>
            </div>

            <Slider v-modl="form.minmatch" :max="0.9" :step="0.01" :marks="marks1"></Slider>
          </li>
        </ul>
      </template>
    </CommonCollapse>
    <Divider></Divider>

    <CommonCollapse title="输出" tip="大模型运行完成后生成的内容">
      <el-tree default-expand-all :data="form.commonoutvo">
        <template #default="{ node, data }">
          <div class="panel-table">
            <div class="flex items-center">
              <span class="text-sm">{{ data.varname }}</span>

              <div class="text-bg-normal">{{ data.vartype }}</div>
            </div>
          </div>
        </template>
      </el-tree>
    </CommonCollapse>

    <KnowledgeSelect v-model="showModal" :form="form" :skillList="skillList" @cancel="showModal = false" />
  </Drawer>
</template>
<script setup>
import { ref, computed } from 'vue'
import { Handle, Position, useNode, useVueFlow } from '@vue-flow/core'
import { myKnowledge } from '@/api/modules/knowledgeBase'
import { flowUpload } from '@/api/modules/flow'

import CommonCollapse from '@/components/CommonCollapse/index.vue'
import KnowledgeSelect from '@/components/FlowCanvas/components/dialog/KnowledgeSelect.vue'

import {
  DOCSTRATEGY_OPTIONS,
  SEGMENTATION_OPTONS,
  SYMBOL_TYPE_OPTIONS,
  PRECISE_OPTIONS
} from '../../lib/constant'

const props = defineProps({
  form: {
    type: Object,
    default: () => {}
  },
  title: {
    type: String,
    default: '输出'
  },
  desc: String
})

const emit = defineEmits(['add', 'remove', 'cancel'])
const node = useNode()
const visible = ref(false)
const showModal = ref(false)
const marks = ref({
  100: {
    style: {
      color: '#000'
    },
    label: '100'
  },
  850: {
    style: {
      'font-size': '14px',
      'margin-left': '16px'
    },
    label: 'Default'
  },
  5000: {
    style: {
      color: '#000'
    },
    label: '5000'
  }
})

const marks1 = ref({
  0: {
    style: {
      color: '#000'
    },
    label: '0'
  },
  0.1: {
    style: {
      'font-size': '14px',
      'margin-left': '16px'
    },
    label: 'Default'
  },
  0.9: {
    style: {
      color: '#000'
    },
    label: '0.9'
  }
})

const checkOptions = ref([
  {
    name: '图片元素',
    value: false
  },
  {
    name: '扫描件 (OCR)',
    value: false
  },
  {
    name: '表格元素',
    value: false
  }
])

// 组件的增删
const addInput = (listKey) => {
  emit('add', listKey)
}
const removeInput = (listKey, index) => {
  if (listKey == 'outputList' && index == 0) return
  emit('remove', listKey, index)
}
const init = () => {
  visible.value = true
}
const cancel = () => {
  visible.value = false
  emit('cancel')
}

const skillList = ref([])
const getKnowledgeList = async () => {
  const { data } = await myKnowledge.catePage({
    query: {
      p: 1,
      ps: 1000
    },
    data: {
      aitype: 'kb'
    }
  })
  skillList.value = data.topicList
}
getKnowledgeList()

const knowledgeList = computed(() => {
  return skillList.value.filter((item) => props.form.knowledgeid.includes(item.id))
})

const fileLoading = ref(false)
const beforeUpload = (file) => {
  props.form.inoutlist[0].varparam = file.name
  fileLoading.value = true
  flowUpload({
    upload: file,
    id: node.id
  }).then(({data})=>{

  }).finally(()=>{
    fileLoading.value = false
  })

  return false
}

defineExpose({
  init,
  knowledgeList
})
</script>
<style lang="scss" scoped>
@import '@/assets/styles/mixin.scss';

@keyframes rotateAnimation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.faid-type {
  background-color: #eff0f7;
  padding: 2px 4px;
  font-size: 12px;
}
.upload-btn {
  display: flex;
  align-items: center;
  border: 1px solid #cfd2df;
  border-radius: 4px;
  height: 32px;
  .ivu-icon-ios-folder-outline {
    padding: 0 4px;
    border-right: 1px solid #cfd2df;
    height: 100%;
    line-height: 32px;
  }
  .ivu-upload {
    height: 100%;
    flex: 1;
    :deep(.ivu-upload-select) {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      font-size: 12px;
    }
  }
  .file-context {
    display: flex;
    justify-content: space-between;
    flex: 1;
    align-items: center;
    padding: 0 8px;
    background-color: #d3d7e5;
    >span{
      @include text-ellipsis();
      width: 108px;
    }
    .ivu-icon-ios-close {
      margin-left: 4px;
      &:hover {
        opacity: 0.8;
      }
    }

    .ivu-icon-ios-loading{
      animation: rotateAnimation .8s linear infinite;
    }
  }
}
.ans-type {
  margin-top: 8px;
  li {
    border: 1px solid #d1d4df;
    border-radius: 8px;
    padding: 8px 12px;
    flex: 1;
    display: flex;
    align-items: center;
    cursor: pointer;
    font-size: 12px;
    &:hover::before {
      background-color: #f2f3f7;
    }
    &::before {
      content: '';
      display: block;
      width: 16px;
      height: 16px;
      border-radius: 50%;
      border: 1px solid #d1d4df;
      margin-right: 8px;
    }
    &:nth-child(n + 2) {
      margin-left: 8px;
    }
    &.avtive {
      background-color: #eceefe;
      border-color: #4f47f6;
      &::before {
        border-width: 5px;
        border-color: #4f47f6;
      }
    }
    > span {
      margin-right: 4px;
    }
  }
}
.custom-selice {
  text-align: right;
  margin-top: 8px;
  :deep(.ivu-input) {
    height: 24px;
    margin-left: auto;
    width: 140px;
  }
}
.ans-label {
  font-size: 12px;
  margin: 12px 0 4px;
}
.panel-table-header {
  align-items: center;
  display: flex;
  gap: 4px;
  padding: 0 4px;

  .name {
    width: 120px;
    margin-right: 6px;
    box-sizing: content-box;
  }
  .center {
    text-align: center;
  }
}

:deep(.ivu-form-item-error-tip){
  font-size: 12px;
}
.panel-table-item {
  height: 30px;
  margin-right: 6px;
  &.center {
    text-align: center;
  }
  &.btn {
    cursor: pointer;
    font-size: 16px;
    font-weight: bold;
    margin-left: 12px;
    height: 22px;
  }
}

.el-tree-node__content {
  margin-top: 16px;
}

.knowledge-gather {
  > li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #e9ebf1;
    border-radius: 8px;
    padding: 10px;
    cursor: pointer;
    &:hover {
      background-color: #f6f6fb;
      .ivu-btn {
        display: block;
      }
    }
    &:nth-child(n + 2) {
      margin-top: 8px;
    }
    .label {
      display: flex;
      align-items: center;
      color: #0f1528d1;
      font-weight: 500;
      img {
        width: 30px;
        height: 30px;
        margin-right: 12px;
      }
    }
    :deep(.ivu-btn) {
      display: none;
      height: 30px;
      line-height: 1;
      .ivu-icon {
        font-size: 20px;
      }
    }
  }
}

.strategy-content {
  > li {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 24px;
    .label {
      font-size: 12px;
      .ivu-tooltip {
        margin-left: 4px;
        cursor: pointer;
      }
    }
    .ivu-select,
    .ivu-slider {
      width: 140px;
    }
  }
}

.checkbox-content {
  display: flex;
  flex-direction: column;
  .ivu-checkbox-wrapper {
    margin-top: 12px;
    :deep(.ivu-checkbox-label-text) {
      margin-left: 4px;
    }
  }
}
</style>
